package dao;

import java.util.ArrayList;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

public class WaitingDAO {
	private EntityManager em;
	
	public WaitingDAO(EntityManager em) {
		this.em = em;
	}
	
	public void updateEntityManager(EntityManager em){
		this.em = em;
	}
	
	public Waiting searchCode(int oid){
		Query query = em.createNamedQuery("searchWaitingCode");
	    query.setParameter("code", oid);
	    return (Waiting) query.getSingleResult();
	}

	public ArrayList<Waiting> searchWaiting(Date dateS, Date dateE){
		Query query = em.createNamedQuery("searchWaitingDate");
	    query.setParameter("dateS", dateS);
	    query.setParameter("dateE", dateE);
	    
	    ArrayList<Waiting> colWaiting = (ArrayList<Waiting>)query.getResultList();
	    return colWaiting;
	}
	
	public Waiting searchWaiting(Waiting waiting){
		Query query = em.createNamedQuery("searchWaiting");
	    //query.setParameter("code", waiting.getOID());
	    query.setParameter("date", waiting.getDhWaiting());
	    
	    ArrayList<Waiting> colWaiting = (ArrayList<Waiting>) query.getResultList();
	    
	    for(Waiting w :colWaiting){
	    	if(w.getCustomer().getOID() == waiting.getCustomer().getOID()){
	    		return w;
	    	}
	    }
	    return null;
	}
	
	public boolean save(Waiting waiting){		
		EntityTransaction trans = em.getTransaction();
		trans.begin();

		try{
			if (em.find(Waiting.class,waiting.getOID()) != null){
				em.merge(waiting);
			}else {
				em.persist(waiting);
			}
			trans.commit();
		}catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		}
		
		em.close();
		DAOFactory.getInstance().updateEntityManager();
		
		return true;
	}	

	public boolean remove(Waiting waiting) {
		EntityTransaction trans = em.getTransaction();
		trans.begin();
		
		try{
			em.remove(waiting);	
			trans.commit();		
		}catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		}
		
		em.close();
		DAOFactory.getInstance().updateEntityManager();
		
		return true;
	}
}








